import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 布局组件
import Layout from '@/layout/Layout.vue'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard', // 默认跳转到首页
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', requiresAuth: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人信息', requiresAuth: true }
      },
      {
        path: 'change-password',
        name: 'ChangePassword',
        component: () => import('@/views/profile/change-password.vue'),
        meta: { title: '修改密码', requiresAuth: true }
      }
    ]
  },
  // 课程教学总结管理
  {
    path: '/kcjxzj',
    component: Layout,
    redirect: '/kcjxzj/teaching-mission-browse',
    meta: { title: '课程教学总结', requiresAuth: true, icon: 'summary' },
    children: [
      {
        path: 'teaching-mission-browse',
        name: 'KcjxzjTeachingMissionBrowse',
        component: () => import('@/views/kcjxzj/teaching-mission-browse.vue'),
        meta: { title: '浏览教学任务', requiresAuth: true }
      },
      {
        path: 'summary-browse',
        name: 'KcjxzjSummaryBrowse',
        component: () => import('@/views/kcjxzj/summary-browse.vue'),
        meta: { title: '浏览课程总结', requiresAuth: true }
      },
      {
        path: 'summary-create',
        name: 'KcjxzjSummaryCreate',
        component: () => import('@/views/kcjxzj/summary-create.vue'),
        meta: { title: '新建总结', requiresAuth: true }
      },
      {
        path: 'summary-edit/:id',
        name: 'KcjxzjSummaryEdit',
        component: () => import('@/views/kcjxzj/summary-edit.vue'),
        meta: { title: '编辑总结', requiresAuth: true }
      },
      {
        path: 'summary-audit/:id',
        name: 'KcjxzjSummaryAudit',
        component: () => import('@/views/kcjxzj/summary-audit.vue'),
        meta: { title: '审核总结', requiresAuth: true, roles: ['ROLE_RESEARCH_HEAD', 'ROLE_DEPARTMENT_HEAD'] }
      },
      {
        path: 'summary-audit-list',
        name: 'KcjxzjSummaryAuditList',
        component: () => import('@/views/kcjxzj/summary-audit-list.vue'),
        meta: { title: '审核列表', requiresAuth: true, roles: ['ROLE_RESEARCH_HEAD', 'ROLE_DEPARTMENT_HEAD'] }
      }
    ]
  },
  // 教学任务成绩管理（教师用）
  {
    path: '/teaching-mission',
    component: Layout,
    meta: { title: '教学任务', requiresAuth: true },
    children: [
      {
        path: 'score',
        name: 'TeachingMissionScore',
        component: () => import('@/views/teaching-mission/score.vue'),
        meta: { title: '成绩管理', requiresAuth: true, roles: ['ROLE_TEACHER', 'ROLE_ADMIN'] }
      }
    ]
  },
  // 基础数据管理
  {
    path: '/admin/base-data',
    component: Layout,
    redirect: '/admin/base-data/user',
    meta: { title: '基础数据管理', requiresAuth: true, roles: ['ROLE_ADMIN'], icon: 'setting' },
    children: [
      {
        path: 'user',
        name: 'AdminUser',
        component: () => import('@/views/admin/base-data/user.vue'),
        meta: { title: '用户管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'department',
        name: 'AdminDepartment',
        component: () => import('@/views/admin/base-data/department.vue'),
        meta: { title: '单位管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'course',
        name: 'AdminCourse',
        component: () => import('@/views/admin/base-data/course.vue'),
        meta: { title: '课程管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'term',
        name: 'AdminTerm',
        component: () => import('@/views/admin/base-data/term.vue'),
        meta: { title: '学期管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'major-level',
        name: 'AdminMajorLevel',
        component: () => import('@/views/admin/base-data/major-level.vue'),
        meta: { title: '专业层次', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'class',
        name: 'AdminClass',
        component: () => import('@/views/admin/base-data/class.vue'),
        meta: { title: '队次管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'student-registration',
        name: 'AdminStudentRegistration',
        component: () => import('@/views/admin/base-data/student-registration.vue'),
        meta: { title: '学籍管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'student',
        redirect: '/admin/base-data/student-registration',
        meta: { title: '学籍管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'major',
        redirect: '/admin/base-data/major-level',
        meta: { title: '专业层次', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'cengci',
        redirect: '/admin/base-data/major-level',
        meta: { title: '专业层次', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      }
    ]
  },
  // 教学任务管理
  {
    path: '/admin/teaching-mission',
    component: Layout,
    redirect: '/admin/teaching-mission/list',
    meta: { title: '教学任务管理', requiresAuth: true, roles: ['ROLE_ADMIN'], icon: 'education' },
    children: [
      {
        path: 'list',
        name: 'AdminTeachingMission',
        component: () => import('@/views/admin/teaching-mission/teaching-mission.vue'),
        meta: { title: '教学任务管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'students',
        name: 'AdminMissionStudents',
        component: () => import('@/views/admin/teaching-mission/mission-students.vue'),
        meta: { title: '教学任务学员管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'score-components',
        name: 'AdminScoreComponentsList',
        component: () => import('@/views/admin/teaching-mission/score-components-list.vue'), 
        meta: { title: '考核组成', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'score-components/:id',
        name: 'AdminScoreComponents',
        component: () => import('@/views/admin/teaching-mission/score-components.vue'),
        meta: { title: '成绩组成设置', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      },
      {
        path: 'score',
        name: 'AdminScore',
        component: () => import('@/views/admin/teaching-mission/score.vue'),
        meta: { title: '成绩管理', requiresAuth: true, roles: ['ROLE_ADMIN'] }
      }
    ]
  },
  // 403页面
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/403/index.vue'),
    meta: { title: '403 禁止访问', requiresAuth: false }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/404/index.vue'),
    meta: { title: '404', requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
let lastSessionCheck = 0
const SESSION_CHECK_INTERVAL = 5 * 60 * 1000 // 5分钟检查一次

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();

  // 对于需要认证的路由，检查登录状态
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn) {
      // 未登录，跳转到登录页
      next({ path: '/login', query: { redirect: to.fullPath } });
      return;
    }
    
    // 减少会话检查频率：只在距离上次检查超过指定时间间隔时才检查
    const now = Date.now()
    if (now - lastSessionCheck > SESSION_CHECK_INTERVAL) {
      try {
        const isSessionValid = await userStore.checkSessionValidity();
        lastSessionCheck = now
        
        if (!isSessionValid) {
          // 会话无效，跳转到登录页
          next({ path: '/login', query: { redirect: to.fullPath } });
          return;
        }
      } catch (error) {
        // 验证过程出错，但不强制跳转，让用户继续操作
        // 如果真的有问题，后续的API请求会处理
      }
    }
    
    // 检查角色权限
    if (to.meta.roles && !userStore.isAdmin && !to.meta.roles.some(role => userStore.roles.includes(role))) {
      next({ path: '/403' }); // 无权限页面
      return;
    }
  }
  
  next();
});

export default router
